let logger = require("pomelo-logger").getLogger(__filename);
let pomelo = require("pomelo");
let COMPONENT_NAME = "connectionComponent";

let ConnectionComponent = function (owner) {
    this.owner = owner;
    this.frontendId = "";
    this.sessionId = 0;
};

ConnectionComponent.prototype.setConnectionId = function (session) {
    this.frontendId = session['frontendId'];
    this.sessionId = session['id'];
};

ConnectionComponent.prototype.clearConnectionId = function () {
    this.frontendId = "";
    this.sessionId = 0;
};

ConnectionComponent.prototype.isOnline = function () {
    return this.frontendId !== "" && this.sessionId > 0;
};

ConnectionComponent.prototype.kick = function () {
    pomelo.app.get("backendSessionService").kickBySid(this.frontendId, this.sessionId);
};

ConnectionComponent.prototype.getFrontendId = function() {
    return this.frontendId;
};

ConnectionComponent.prototype.getSessionId = function() {
    return this.sessionId;
};

ConnectionComponent.prototype.getConnectionId = function () {
    return this.frontendId + "_" + this.sessionId;
};

ConnectionComponent.prototype.pushMessage = function (route, message) {
    if (this.isOnline()) {
        pomelo.app.rpcInvoke(this.frontendId, {
            namespace: "user", service: "pushMessageRemote", method: "pushMessage",
            args: [route, message, [this.sessionId]]
        }, function (error, failed) {
        });
    } else {
        logger.error("pushMessage failed..... player is not online. player uid=" + this.owner.getUid() +
            " frontendId=" + this.frontendId +
            " sessionId=" + this.sessionId
        );
    }
};

module.exports.create = function (owner) {
    return new ConnectionComponent(owner);
};
